<!DOCTYPE html>
<html lang="en-us">
  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    
<meta charset="UTF-8">
<title>和 Elasticsearch 交互 | Elasticsearch: 权威指南 | Elastic</title>
<link rel="home" href="index.html" title="Elasticsearch: 权威指南">
<link rel="up" href="intro.html" title="你知道的, 为了搜索…​">
<link rel="prev" href="running-elasticsearch.html" title="安装并运行 Elasticsearch">
<link rel="next" href="_document_oriented.html" title="面向文档">
<meta name="DC.type" content="Learn/Docs/Elasticsearch/Definitive Guide">
<meta name="DC.subject" content="Elasticsearch">
<meta name="DC.identifier" content="2.x">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.optimizely.com/js/18132920325.js"></script>
    <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <meta name="apple-mobile-web-app-title" content="Elastic">
    <meta name="application-name" content="Elastic">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <meta name="naver-site-verification" content="936882c1853b701b3cef3721758d80535413dbfd">
    <meta name="yandex-verification" content="d8a47e95d0972434">
    <meta name="localized" content="true">
    <meta name="st:robots" content="follow,index">
    <meta property="og:image" content="https://www.elastic.co/static/images/elastic-logo-200.png">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon-precomposed" sizes="64x64" href="/favicon_64x64_16bit.png">
    <link rel="apple-touch-icon-precomposed" sizes="32x32" href="/favicon_32x32.png">
    <link rel="apple-touch-icon-precomposed" sizes="16x16" href="/favicon_16x16.png">
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/guide/static/styles.css">
  </head>

  <!--© 2015-2021 Elasticsearch B.V. Copying, publishing and/or distributing without written permission is strictly prohibited.-->

  <body>
    <!-- Google Tag Manager -->
    <script>dataLayer = [];</script><noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-58RLH5" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-58RLH5');</script>
    <!-- End Google Tag Manager -->

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-12395217-16"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'UA-12395217-16');
    </script>

    <!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->
    <script type="text/javascript">
      (function(){var g=function(e,h,f,g){
      this.get=function(a){for(var a=a+"=",c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];" "==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};
      this.set=function(a,c){var b="",b=new Date;b.setTime(b.getTime()+6048E5);b="; expires="+b.toGMTString();document.cookie=a+"="+c+b+"; path=/; "};
      this.check=function(){var a=this.get(f);if(a)a=a.split(":");else if(100!=e)"v"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(":"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case "v":return!1;case "r":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(":")),!c}return!0};
      this.go=function(){if(this.check()){var a=document.createElement("script");a.type="text/javascript";a.src=g;document.body&&document.body.appendChild(a)}};
      this.start=function(){var a=this;window.addEventListener?window.addEventListener("load",function(){a.go()},!1):window.attachEvent&&window.attachEvent("onload",function(){a.go()})}};
      try{(new g(100,"r","QSI_S_ZN_emkP0oSe9Qrn7kF","https://znemkp0ose9qrn7kf-elastic.siteintercept.qualtrics.com/WRSiteInterceptEngine/?Q_ZID=ZN_emkP0oSe9Qrn7kF")).start()}catch(i){}})();
    </script><div id="ZN_emkP0oSe9Qrn7kF"><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>
    <!--END WEBSITE FEEDBACK SNIPPET-->

    <div id="elastic-nav" style="display:none;"></div>
    <script src="https://www.elastic.co/elastic-nav.js"></script>

    <!-- Subnav -->
    <div>
      <div>
        <div class="tertiary-nav d-none d-md-block">
          <div class="container">
            <div class="p-t-b-15 d-flex justify-content-between nav-container">
              <div class="breadcrum-wrapper"><span><a href="/guide/" style="font-size: 14px; font-weight: 600; color: #000;">Docs</a></span></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="main-container">
      <section id="content">
        <div class="content-wrapper">

          <section id="guide" lang="zh_cn">
            <div class="container">
              <div class="row">
                <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                  <!-- start body -->
                  <div class="page_header">
<b>请注意:</b><br>本书基于 Elasticsearch 2.x 版本，有些内容可能已经过时。
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch: 权威指南</a></span>
»
<span class="breadcrumb-link"><a href="getting-started.html">基础入门</a></span>
»
<span class="breadcrumb-link"><a href="intro.html">你知道的, 为了搜索…​</a></span>
»
<span class="breadcrumb-node">和 Elasticsearch 交互</span>
</div>
<div class="navheader">
<span class="prev">
<a href="running-elasticsearch.html">« 安装并运行 Elasticsearch</a>
</span>
<span class="next">
<a href="_document_oriented.html">面向文档 »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="_talking_to_elasticsearch"></a>和 Elasticsearch 交互<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/010_Intro/15_API.asciidoc">edit</a>
</h2>
</div></div></div>
<p>和 Elasticsearch 的交互方式取决于你是否使用 Java</p>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_java_api"></a>Java API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/010_Intro/15_API.asciidoc">edit</a>
</h3>
</div></div></div>
<p>如果你正在使用 Java，在代码中你可以使用 Elasticsearch 内置的两个客户端：</p>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
节点客户端（Node client）
</span>
</dt>
<dd>
节点客户端作为一个非数据节点加入到本地集群中。换句话说，它本身不保存任何数据，但是它知道数据在集群中的哪个节点中，并且可以把请求转发到正确的节点。
</dd>
<dt>
<span class="term">
传输客户端（Transport client）
</span>
</dt>
<dd>
轻量级的传输客户端可以将请求发送到远程集群。它本身不加入集群，但是它可以将请求转发到集群中的一个节点上。
</dd>
</dl>
</div>
<p>两个 Java 客户端都是通过 <em>9300</em> 端口并使用 Elasticsearch 的原生 <em>传输</em> 协议和集群交互。集群中的节点通过端口 9300 彼此通信。如果这个端口没有打开，节点将无法形成一个集群。</p>
<div class="tip admon">
<div class="icon"></div>
<div class="admon_content">
<p>Java 客户端作为节点必须和 Elasticsearch 有相同的 <em>主要</em> 版本；否则，它们之间将无法互相理解。</p>
</div>
</div>
<p>更多的 Java 客户端信息可以在 <a href="/guide/en/elasticsearch/client/index.html" class="ulink" target="_top">Elasticsearch Clients</a> 中找到。</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_restful_api_with_json_over_http"></a>RESTful API with JSON over HTTP<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/010_Intro/15_API.asciidoc">edit</a>
</h3>
</div></div></div>
<p>所有其他语言可以使用 RESTful API 通过端口 <em>9200</em> 和 Elasticsearch 进行通信，你可以用你最喜爱的 web 客户端访问 Elasticsearch 。事实上，正如你所看到的，你甚至可以使用 <code class="literal">curl</code> 命令来和 Elasticsearch 交互。</p>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>Elasticsearch 为以下语言提供了官方客户端--Groovy、JavaScript、.NET、 PHP、 Perl、 Python 和 Ruby—​还有很多社区提供的客户端和插件，所有这些都可以在 <a href="/guide/en/elasticsearch/client/index.html" class="ulink" target="_top">Elasticsearch Clients</a> 中找到。</p>
</div>
</div>
<p>一个 Elasticsearch 请求和任何 HTTP 请求一样由若干相同的部件组成：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">curl -X&lt;VERB&gt; '&lt;PROTOCOL&gt;://&lt;HOST&gt;:&lt;PORT&gt;/&lt;PATH&gt;?&lt;QUERY_STRING&gt;' -d '&lt;BODY&gt;'</pre>
</div>
<p>被 <code class="literal">&lt; &gt;</code> 标记的部件：</p>
<div class="informaltable">
<table border="0" cellpadding="4px">
<colgroup>
<col>
<col>
</colgroup>
<tbody valign="top">
<tr>
<td valign="top">
<p>
<code class="literal">VERB</code>
</p>
</td>
<td valign="top">
<p>
适当的 HTTP <em>方法</em> 或 <em>谓词</em> : <code class="literal">GET</code>、 <code class="literal">POST</code>、 <code class="literal">PUT</code>、 <code class="literal">HEAD</code> 或者 <code class="literal">DELETE</code>。
</p>
</td>
</tr>
<tr>
<td valign="top">
<p>
<code class="literal">PROTOCOL</code>
</p>
</td>
<td valign="top">
<p>
<code class="literal">http</code> 或者 <code class="literal">https</code>（如果你在 Elasticsearch 前面有一个 <code class="literal">https</code> 代理）
</p>
</td>
</tr>
<tr>
<td valign="top">
<p>
<code class="literal">HOST</code>
</p>
</td>
<td valign="top">
<p>
Elasticsearch 集群中任意节点的主机名，或者用 <code class="literal">localhost</code> 代表本地机器上的节点。
</p>
</td>
</tr>
<tr>
<td valign="top">
<p>
<code class="literal">PORT</code>
</p>
</td>
<td valign="top">
<p>
运行 Elasticsearch HTTP 服务的端口号，默认是 <code class="literal">9200</code> 。
</p>
</td>
</tr>
<tr>
<td valign="top">
<p>
<code class="literal">PATH</code>
</p>
</td>
<td valign="top">
<p>
API 的终端路径（例如 <code class="literal">_count</code> 将返回集群中文档数量）。Path 可能包含多个组件，例如：<code class="literal">_cluster/stats</code> 和 <code class="literal">_nodes/stats/jvm</code> 。
</p>
</td>
</tr>
<tr>
<td valign="top">
<p>
<code class="literal">QUERY_STRING</code>
</p>
</td>
<td valign="top">
<p>
任意可选的查询字符串参数 (例如 <code class="literal">?pretty</code> 将格式化地输出 JSON 返回值，使其更容易阅读)
</p>
</td>
</tr>
<tr>
<td valign="top">
<p>
<code class="literal">BODY</code>
</p>
</td>
<td valign="top">
<p>
一个 JSON 格式的请求体 (如果请求需要的话)
</p>
</td>
</tr>
</tbody>
</table>
</div>
<p>例如，计算集群中文档的数量，我们可以用这个:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">curl -XGET 'http://localhost:9200/_count?pretty' -d '
{
    "query": {
        "match_all": {}
    }
}
'</pre>
</div>
<p>Elasticsearch 返回一个 HTTP 状态码（例如：<code class="literal">200 OK</code>）和（除`HEAD`请求）一个 JSON 格式的返回值。前面的 <code class="literal">curl</code> 请求将返回一个像下面一样的 JSON 体：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "count" : 0,
    "_shards" : {
        "total" : 5,
        "successful" : 5,
        "failed" : 0
    }
}</pre>
</div>
<p>在返回结果中没有看到 HTTP 头信息是因为我们没有要求`curl`显示它们。想要看到头信息，需要结合 <code class="literal">-i</code> 参数来使用 <code class="literal">curl</code> 命令：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">curl -i -XGET 'localhost:9200/'</pre>
</div>
<p>在书中剩余的部分，我们将用缩写格式来展示这些 <code class="literal">curl</code> 示例，所谓的缩写格式就是省略请求中所有相同的部分，例如主机名、端口号以及 <code class="literal">curl</code> 命令本身。而不是像下面显示的那样用一个完整的请求：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">curl -XGET 'localhost:9200/_count?pretty' -d '
{
    "query": {
        "match_all": {}
    }
}'</pre>
</div>
<p>我们将用缩写格式显示：</p>
<div class="pre_wrapper lang-sense">
<pre class="programlisting prettyprint lang-sense">GET /_count
{
    "query": {
        "match_all": {}
    }
}</pre>
</div>
<div class="sense_widget" data-snippet="snippets/010_Intro/15_Count.json"></div>
<p>事实上， <a class="xref" href="running-elasticsearch.html#sense" title="安装 Sense">Sense 控制台</a> 也使用这样相同的格式。如果你正在阅读这本书的在线版本,可以通过点击 Sense 链接视图在 Sense 上打开和运行示例代码。</p>
</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="running-elasticsearch.html">« 安装并运行 Elasticsearch</a>
</span>
<span class="next">
<a href="_document_oriented.html">面向文档 »</a>
</span>
</div>
</div>

                  <!-- end body -->
                </div>
                <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                  <div id="rtpcontainer" style="display: block;">
                    <div class="mktg-promo">
                      <h3>Most Popular</h3>
                      <ul class="icons">
                        <li class="icon-elasticsearch-white"><a href="https://www.elastic.co/webinars/getting-started-elasticsearch?baymax=default&amp;elektra=docs&amp;storm=top-video">Get Started with Elasticsearch: Video</a></li>
                        <li class="icon-kibana-white"><a href="https://www.elastic.co/webinars/getting-started-kibana?baymax=default&amp;elektra=docs&amp;storm=top-video">Intro to Kibana: Video</a></li>
                        <li class="icon-logstash-white"><a href="https://www.elastic.co/webinars/introduction-elk-stack?baymax=default&amp;elektra=docs&amp;storm=top-video">ELK for Logs &amp; Metrics: Video</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

        </div>


<div id="elastic-footer"></div>
<script src="https://www.elastic.co/elastic-footer.js"></script>
<!-- Footer Section end-->

      </section>
    </div>

<script src="/guide/static/jquery.js"></script>
<script type="text/javascript" src="/guide/static/docs.js"></script>
<script type="text/javascript">
  window.initial_state = {}</script>
  </body>
</html>
